import Vue from 'vue'
import Vuex from 'vuex'
import queryString from 'query-string'
import user from '@/store/modules/user'
import evaluate from '@/store/modules/evaluate'
import { defaultPid, defaultPlatform, serviceLink, xyAlipayAppId } from '@/config'
import apis from '@/apis'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		pid: defaultPid,
		platform: defaultPlatform,
		commonAgrs: {},
		systemInfo: uni.getSystemInfoSync() || {},
		userLocation: uni.getStorageSync('hsb_user_location') || {},
		// #ifdef WEB
		userSelectLocation: JSON.parse(sessionStorage.getItem('hsb_select_city') || '{}'),
		// #endif
		// #ifndef WEB
		userSelectLocation: {},
		// #endif
		hsbAddress: {}
	},
	mutations: {
		setData (state, { key, value }) {
			state[key] = value
		}
	},
	actions: {
		/*
		 * 获取位置信息
		*/
		getUserLocation ({ state, commit, dispatch }, callBack) {
			// if (state.userLocation.longitude && state.userLocation.latitude) {
			// 	return dispatch('getUserLocationAddress')
			// }
			uni.getLocation({
				complete: (data) => {
					console.log(data)
					// data.latitude = '23.125177'
					// data.longitude = '113.28064'
					const { longitude, latitude } = data || {}
					if (longitude && latitude) {
						const value = {
							longitude,
							latitude,
							location: `${longitude},${latitude}`
						}
						commit('setData', {
							key: 'userLocation',
							value
						})
						uni.setStorageSync('hsb_user_location', value)
					}
					if (typeof callBack === 'function') {
						callBack(state.userLocation)
					}
					dispatch('getUserLocationAddress')
				}
			})
		},
		/*
		 * 获取当前城市小站信息
		*/
		async getUserLocationAddress ({ state, commit }) {
			const [res] = await apis.getCityStoreInfo({
				longitude: state.userLocation.longitude || '-1',
				latitude: state.userLocation.latitude || '-1'
			})
			if (res._errCode === '0') {
				const value = {
					...state.userLocation,
					address: {
						city: res._data.cityName || '',
						cityCode: res._data.cityCode || ''
					}
				}
				commit('setData', {
					key: 'userLocation',
					value
				})
				uni.setStorageSync('hsb_user_location', value)
			}
		},
		/*
		 * 回收宝公司地址
		*/
		async getHsbAddress ({ commit }) {
			const [res] = await apis.getDeliveryAddress()
			if (res._errCode === '0') {
				commit('setData', {
					key: 'hsbAddress',
					value: res._data || {}
				})
			}
		},
		/*
		 * 联系客服
		*/
		contactService () {
			// #ifdef WEB
			window.location.href = serviceLink
			// #endif
			// #ifndef WEB
			uni.navigateTo({
				url: `/pages/webview/index?webUrl=${encodeURIComponent(serviceLink)}&needQuery=0`
			})
			// #endif
		},
		/*
		 * 页面跳转
		 * h5/应用页面/三方小程序
		*/
		openPage ({ rootState }, { redirectUrl }) {
			if (!redirectUrl) return
			// #ifdef MP-WEIXIN || MP-ALIPAY
			if (/^othermini/.test(redirectUrl)) {
				const miniParamStr = redirectUrl.split('?')[1] || ''
				const querys = queryString.parse(miniParamStr)
				const targetParams = {
					appId: querys.appid,
				}
				if (querys.path) {
					targetParams.path = decodeURIComponent(querys.path)
				}
				return uni.navigateToMiniProgram(targetParams)
			}
			if (/^xymini/.test(redirectUrl)) {
				const webUrl = decodeURIComponent(redirectUrl.split('?')[1] || '')
				return uni.navigateToMiniProgram({
					appId: xyAlipayAppId,
					path: 'pages/webview/index?url=' + encodeURIComponent(webUrl),
					extraData: {
						flag: true,
						url: '',
						outId: '2018061460365359',
						backParam: ''
					}
				})
			}
			// #endif
			if (/^\/pages*/.test(redirectUrl)) {
				return uni.navigateTo({
					url: redirectUrl
				})
			}
			if (/^http[s]*/.test(redirectUrl)) {
				// #ifdef WEB
				const { pid, platform } = rootState
				const { token = '' } = rootState.user.userInfo
				window.location.href = `${redirectUrl}${redirectUrl.indexOf('?') === -1 ? '?' : '&'}${queryString.stringify({ pid, platform, token })}`
				// #endif
				// #ifndef WEB
				return uni.navigateTo({
					url: `/pages/webview/index?webUrl=${encodeURIComponent(redirectUrl)}`
				})
				// #endif
			}
		}
	},
	modules: {
		user,
		evaluate
	}
})

export default store